package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.CommentMapper;
import cn.tedu.weibo.mapper.WeiboMapper;
import cn.tedu.weibo.pojo.dto.WeiboDto;
import cn.tedu.weibo.pojo.entity.Weibo;
import cn.tedu.weibo.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/weibo/")
public class WeiboController {
    @Autowired
    WeiboMapper mapper;
    @RequestMapping("insert")
    public int insert(@RequestBody WeiboDto weiboDto, HttpSession session) {
        System.out.println("weiboDto = " + weiboDto);
        // 得到当前登录的用户对象
        UserVo user = (UserVo) session.getAttribute("user");
        if(user == null) {
            return 2;  // 代表未登录
        }
        // 往数据库里存的时候需要使用entity
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDto, weibo);
        // 给weibo对象的其它属性赋值
        weibo.setUserId(user.getId()); // 设置当前登录的用户id为发布者id
        weibo.setCteated(new Date()); // 设置当前时间为发布时间
        System.out.println("weibo=" + weibo);
        mapper.insert(weibo);
        return 1;
    }
    @RequestMapping("select")
    public List<WeiboIndexVo> select() {
        return mapper.select();
    }
    @RequestMapping("selectById")
    public WeiboDetailVo selectById(int id) {
        return mapper.selectById(id);
    }
    @RequestMapping("select/mine")
    public ResultVo selectMine(HttpSession session) {
        UserVo user = (UserVo) session.getAttribute("user");
        if(user == null) {
            return new ResultVo(2,"用户未登录",null);
        }
        // 如果没有发过微博响应的会是一个空集合, 客户端接受到底的是一个空字符串
        return new ResultVo(1, "成功", mapper.selectMine(user.getId()));
    }
    @Autowired
    CommentMapper commentMapper;
    @RequestMapping("delete")
    public void delete(int id) {
        // 删除相关评论
        commentMapper.deleteByWeiboId(id);
        // 删除微博
        mapper.deleteById(id);
    }

}
